﻿using DotNetCore.CAP;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.EmailHelper;
using NP.BPMReportPlatform.Entities.BPM_EngineEventBus;
using NP.BPMReportPlatform.FlowManagement;
using NP.BPMReportPlatform.RecurringJobs.Dto;
using NPOI.XWPF.UserModel;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Net.Mail;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
using Ubiety.Dns.Core;

namespace NP.BPMReportPlatform.BPMEngine
{
    /// <summary>
    /// 引擎接口服务
    /// </summary>
    public class EngineAppService : BPMReportPlatformAppService, IEngineAppService
    {
        private readonly SqlSugarClient _dbEngineEventBus, _dbEngineEventBus2;
        private ICapPublisher _capBus;
        private readonly IEmailAPPService _emailAPPService;
        private readonly string _engineExceptionNoticeEmail;


        public EngineAppService(ISqlSugarAppService sqlSugarAppService, ICapPublisher publisher,
            IConfiguration configuration, IEmailAPPService emailAPPService)
        {
            _dbEngineEventBus = sqlSugarAppService.GetEngineEventBusInstance();
            _dbEngineEventBus2 = sqlSugarAppService.GetEngineEventBus2Instance();
            _capBus = publisher;
            _emailAPPService = emailAPPService;
            _engineExceptionNoticeEmail = configuration["PlatformManager:EngineExceptionNoticeEmail"];
        }

        /// <summary>
        /// 获取当前引擎队列数量
        /// </summary>
        /// <returns></returns>
        public async Task GetEngineCount()
        {
            var cnt = await _dbEngineEventBus.Queryable<Received>().With(SqlWith.NoLock).Where(x => x.StatusName.Equals("Scheduled")).CountAsync();
            var cnt2 = await _dbEngineEventBus2.Queryable<Received>().With(SqlWith.NoLock).Where(x => x.StatusName.Equals("Scheduled")).CountAsync();
            if (cnt > 20 || cnt2 > 20)
            {
                var topic = $"【引擎堵塞】（引擎1：{cnt}，引擎2：{cnt2}）新BPM引擎队列异常！！！";
                var content = _emailAPPService.GenerateEmailTemplate("EngineExceptionEmail.cshtml");
                await _capBus.PublishAsync(
                  "bpmnew.EmailAppService.SendEmailAsync",
                  new SendEmailSimpleDto()
                  {
                      To = _engineExceptionNoticeEmail,
                      Subject = topic,
                      Body = content
                  });
            }
        }

        /// <summary>
        /// 获取当前引擎队列失败数量
        /// </summary>
        /// <returns></returns>
        public async Task GetEngineFailedCount()
        {
            var dtNow = DateTime.Now.AddMinutes(-5);
            var engine1List = await _dbEngineEventBus.Queryable<Received>().With(SqlWith.NoLock).Where(x => x.StatusName.Equals("Failed") && x.Added >= dtNow).ToListAsync();
            var engine2List = await _dbEngineEventBus2.Queryable<Received>().With(SqlWith.NoLock).Where(x => x.StatusName.Equals("Failed") && x.Added >= dtNow).ToListAsync();
            if (engine1List.Count > 0 || engine2List.Count > 0)
            {
                var topic = $"【引擎失败】（引擎1：{engine1List.Count}，引擎2：{engine2List.Count}）";
                var sbContentText = new StringBuilder();
                sbContentText.AppendLine("近5分钟有引擎执行失败，请及时查看！！！");
                if (engine1List.Count > 0)
                {
                    sbContentText.AppendLine($"Engine1Json：{JsonConvert.SerializeObject(engine1List)}");
                }
                if (engine2List.Count > 0)
                {
                    sbContentText.AppendLine($"Engine2Json：{JsonConvert.SerializeObject(engine2List)}");
                }
                await _capBus.PublishAsync(
                  "bpmnew.EmailAppService.SendEmailAsync",
                  new SendEmailSimpleDto()
                  {
                      To = _engineExceptionNoticeEmail,
                      Subject = topic,
                      Body = sbContentText.ToString()
                  });
            }
        }
    }
}
